import { Router } from 'express'
import CategoryDao from '../dao/CategoryDao.js'
import Category from '../verify/Category.js'

let router = Router()

router.route('/api/category')
    .post(async (req, res) => {
        let category = Category.insertObj(req.body)
        if (!category) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await CategoryDao.insert(category)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

    .delete(async (req, res) => {
        let category = Category.deleteObj(req.body)
        if (!category) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await CategoryDao.delete(category)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

    .put(async (req, res) => {
        let category = Category.updateObj(req.body)
        if (!category) return res.end(JSON.stringify({ code: 500, msg: '参数有误' }))

        let result = await CategoryDao.update(category)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200 }))
    })

router
    .get('/api/category/:id', async (req, res) => {
        let result = await CategoryDao.selectById(req.params.id)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/categoryByPage/:pageIndex/:pageSize', async (req, res) => {
        let { pageIndex, pageSize } = req.params

        let result = await CategoryDao.selectByLimit((pageIndex - 1) * pageSize, pageSize)
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

    .get('/api/categoryTotal', async (req, res) => {
        let result = await CategoryDao.selectCount()
        if (result instanceof Error) return res.end(JSON.stringify({ code: 500, msg: '数据库操作失败' }))

        return res.end(JSON.stringify({ code: 200, data: result }))
    })

export default router